package com.geeyuu.android.utils;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.android.camera.CropImage;
import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;

public class AndroidUtil {
    
    public static Intent getCropIntent(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, CropImage.class);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("setWallpaper", false);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("outputX", 640);
        intent.putExtra("outputY", 640);
        return intent;
    }
    
    public static Bitmap getThumbBitmap(Context context, Bitmap bitmap){
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int smallSize;
        if (screenWidth < 480) {
            smallSize = ImageLoder.IMG_SIZE_75;
        } else if (screenWidth <= 640) {
            smallSize = ImageLoder.IMG_SIZE_150;
        } else {
            smallSize = ImageLoder.IMG_SIZE_300;
        }
        return ThumbnailUtils.extractThumbnail(bitmap, smallSize, smallSize);
    }
    
    public static void showToast(final Context context, final String msg){
        new Handler(context.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }, 100);
    }
    
    public static void showToast(final Context context, final int msgResId){
        new Handler(context.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msgResId, Toast.LENGTH_SHORT).show();
            }
        }, 100);
    }
    
    public static void unlogin(Context context){
        GeePrefrence.setMyUid(context, 0l);
        GeePrefrence.setMySessionId(context, 0l);
        GeePrefrence.setLoginServerTime(context, 0l);
        GeePrefrence.setAccountName(context, "");
        GeePrefrence.setPWD(context, "");
    }
    
    public static synchronized boolean isSessionTimeOut(Context context){
        if(GeePrefrence.getMyUid(context) > 0 && GeePrefrence.getMySessionId(context) == 0 && GeePrefrence.getIsUserRegisted(context)){
            return true;
        }
        return false;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (null != networkInfo) {
            return networkInfo.isAvailable() && networkInfo.isConnected();
        } else {
            return false;
        }
    }

    public static String getDeviceId(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();
        if (deviceId == null) {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            deviceId = info.getMacAddress();
        }
        return deviceId;
    }

    /**
     * 单位km
     * @param context
     * @param friendLocation
     * @return
     */
    public static float getDistanceWithMe(Context context, String friendLocation) {
        if (CommonUtil.isEmpty(friendLocation)) {
            LogUtil.e("AndroidUtil", "参数为空");
            return 0.0f;
        }
        String myLocation = GeePrefrence.getMyLocation(context);
        if (CommonUtil.isEmpty(myLocation)) {
            LogUtil.e("AndroidUtil", "my location 为 空");
            return 0.0f;
        }
        String[] friendLonAndLat = friendLocation.split(",");
        if (friendLonAndLat != null && friendLonAndLat.length == 2) {
            String[] myLonAndLat = myLocation.split(",");
            if (myLonAndLat != null && myLonAndLat.length == 2) {
                float[] distance = new float[1];
                Location.distanceBetween(Double.valueOf(myLonAndLat[1]), Double.valueOf(myLonAndLat[0]),
                        Double.valueOf(friendLonAndLat[1]), Double.valueOf(friendLonAndLat[0]), distance);
                String distanceStr = String.valueOf(distance[0] * 0.001f);
                int dotIndex = distanceStr.indexOf(".");
                if(dotIndex > 0){
                    return Float.valueOf(distanceStr.substring(0, dotIndex + 2));
                }else{
                    return Float.valueOf(distanceStr);
                }
            } else {
                LogUtil.e("AndroidUtil", "my location 数组有问题");
            }
        } else {
            LogUtil.e("AndroidUtil", "friendLocation 数组有问题");
        }
        return 0.0f;
    }

    public static void showMyToast(Context context, String tips) {
        Toast toast = Toast.makeText(context, tips, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static void showMyToast(Context context, int resId) {
        Toast toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static int getSimCardNetWorkType(Context context) {
        TelephonyManager telmanager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int type = telmanager.getNetworkType();
        return type;
    }

    public static boolean isSdCardValid() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public static void hideKeyBoard(Context context) {
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
    }

    public static boolean createApplicationFolder(Context context) {
        if (!isSdCardValid()) {
            return false;
        }
        File file = null;
        int length = GeeConstants.PATHS.length;
        for (int i = 0; i < length; i++) {
            file = new File(GeeConstants.PATHS[i]);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
        }
        return true;
    }

    public static final int MB10 = 1024 * 1024 * 10;
    public static final int MB5 = 1024 * 1024 * 5;

    public static long getSdCardAvailSize() {
        long size = 0;
        if (isSdCardValid()) {
            File sdcardFile = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(sdcardFile.getPath());
            int availableBlocks = statFs.getAvailableBlocks();
            int blockSize = statFs.getBlockSize();
            size = availableBlocks * blockSize;
        }
        return size;
    }

    // public static void startHeartBeat(Context context, long interval){
    // Intent intent = new Intent();
    // intent.setAction(AppConstants.RECEIVER_ACTION_HEART_BEAT);
    // intent.setPackage(context.getPackageName());
    // PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
    // intent, PendingIntent.FLAG_UPDATE_CURRENT);
    // AlarmManager am =
    // (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    // am.cancel(pendingIntent);
    // am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +
    // 5000, interval, pendingIntent);
    // }

    public static final int NETWORK_TYPE_MOBILE = ConnectivityManager.TYPE_MOBILE;
    public static final int NETWORK_TYPE_WIFI = ConnectivityManager.TYPE_WIFI;

    public static int getActiveNetworkType(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (null != networkInfo) {
            return networkInfo.getType();
        } else {
            return -1;
        }
    }

    public static void installPackage(Context context, String filePath) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale);
    }

    // public static GeoPoint parseGeoPoint(HashMap<String, Object> hashMap) {
    // GeoPoint geoPoint = null;
    //
    // try {
    // Object object1 = hashMap.get("longitude");
    // Object object2 = hashMap.get("latitude");
    //
    // if (object1 != null && object2 != null) {
    // String string1 = (String) object1;
    // String string2 = (String) object2;
    //
    // geoPoint = new GeoPoint((int) (Double.parseDouble(string1) * 1000000),
    // (int) (Double.parseDouble(string2) * 1000000));
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    //
    // if (geoPoint == null) {
    // return new GeoPoint();
    // } else {
    // return geoPoint;
    // }
    // }

}
